package com.dingshi.security;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.dingshi.security.adapter.GuardAdapter;
import com.dingshi.security.api.ApiResult;
import com.dingshi.security.api.ApiReturnResultListener;
import com.dingshi.security.api.ShiftChangeApi;
import com.dingshi.security.db.SettingLoader;
import com.dingshi.security.entity.GuardEntity;
import com.dingshi.security.entity.ShiftChange;
import com.dingshi.security.util.Base64;
import com.dingshi.security.util.Utils;
import com.dingshi.security.view.LoadDialog;
import com.dingshi.security.view.WritePadDialog;
import com.dingshi.security.view.WritePadDialog.DialogListener;

public class ShiftChangeActivity extends BaseActivity implements
		OnClickListener ,OnItemSelectedListener{

	private static final int ID_LOADING = 2013;
	private Button btn_back;
	private TextView title_text;
	private Button btn_right;
	private TextView edit_deparment;
	private ImageView edit_duty_man;
	private ImageView edit_device;
	private ImageView edit_break;
	private Spinner job_spinner;
	private Spinner instrument_spinner;
	private Spinner equipment_spinner;
	private Spinner hygiene_spinner;
	private EditText edit_job_assets;
	private EditText edit_instrument;
	private EditText edit_equipment;
	private EditText edit_hygiene;//TODO 暂时不用
	private Spinner carry_spinner;
	private TextView btn_sign_jiaoban;
	private TextView btn_sign_jieban;
	private TextView btn_sign_banzhang;
	protected ArrayList<GuardEntity> guardList;
	private String s1,s2,s3;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shift_change);
		initTitle();
		initComponents();
		registerButton();
		
		getCarray();
	}

	private void getCarray() {
		ShiftChangeApi api = new ShiftChangeApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {
			
			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				JSONObject jsonEntity = apiResult.getJsonEntity();
				Log.e("aa", jsonEntity.toString());
				if (jsonEntity != null) {

					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							break;
						case 1:// 数组
							JSONArray array = jsonEntity.getJSONArray("d");
							if (array != null) {
								guardList = new ArrayList<GuardEntity>();
								GuardEntity guard = null;
								for (int i = 0; i < array.length(); i++) {
									guard = new GuardEntity();
									JSONObject opt = (JSONObject) array.opt(i);
									String nid = opt.getString("nid");
									if(!Utils.isNullOrEmpty(nid)&&!nid.equals(SettingLoader.getGuardNum(ShiftChangeActivity.this))) {
										guard.setN(opt.getString("n"));
										guard.setNid(nid);
										guardList.add(guard);
									}
								}
							}
							break;
						case -1:// 错误
							break;

						default:
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
					GuardAdapter adapter = new GuardAdapter(ShiftChangeActivity.this,guardList);
					carry_spinner.setAdapter(adapter);
				}
			}
			
			@Override
			public <T> void onReturnLoading(int requestCode) {
				
			}
			
			@Override
			public <T> void onReturnFailResult(int requestCode, ApiResult<T> apiResult) {
				
			}
		});
		api.getShiftList(1, SettingLoader.getDepartNum(this), this);
		
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ID_LOADING:
			LoadDialog dialog = new LoadDialog(this, "努力加载中。。。");
			return dialog;

		default:
			break;
		}
		return super.onCreateDialog(id);
	}
	
	
	private void initTitle() {
		btn_back = (Button) findViewById(R.id.btn_back);
		title_text = (TextView) findViewById(R.id.title_text);
		btn_right = (Button) findViewById(R.id.btn_refresh);
		title_text.setText("交接班");
		btn_right.setVisibility(View.VISIBLE);
		btn_right.setText("交接");

	}

	private void registerButton() {
		btn_right.setOnClickListener(this);
		btn_back.setOnClickListener(this);

		edit_duty_man.setOnClickListener(signListener1);
		btn_sign_jiaoban.setOnClickListener(signListener1);
		edit_device.setOnClickListener(signListener2);
		btn_sign_jieban.setOnClickListener(signListener2);
		edit_break.setOnClickListener(signListener3);
		btn_sign_banzhang.setOnClickListener(signListener3);
		
		job_spinner.setOnItemSelectedListener(this);
		instrument_spinner.setOnItemSelectedListener(this);
		equipment_spinner.setOnItemSelectedListener(this);
	}

	private void initComponents() {
		edit_deparment = (TextView) findViewById(R.id.edit_deparment);// 交班人员
		carry_spinner = (Spinner) findViewById(R.id.carry_spinner);// 接班人员
		edit_duty_man = (ImageView) findViewById(R.id.edit_duty_man);// 交班签字
		edit_device = (ImageView) findViewById(R.id.edit_device);// 接班签字
		edit_break = (ImageView) findViewById(R.id.edit_break);// 班长签字
		
		btn_sign_jiaoban = (TextView)findViewById(R.id.btn_sign_jiaoban);
		btn_sign_jieban = (TextView)findViewById(R.id.btn_sign_jieban);
		btn_sign_banzhang = (TextView)findViewById(R.id.btn_sign_banzhang);
		

		job_spinner = (Spinner) findViewById(R.id.spinner1);
		instrument_spinner = (Spinner) findViewById(R.id.spinner2);
		equipment_spinner = (Spinner) findViewById(R.id.spinner3);
		hygiene_spinner = (Spinner) findViewById(R.id.spinner4);

		edit_job_assets = (EditText) findViewById(R.id.edit_job_assets);
		edit_instrument = (EditText) findViewById(R.id.edit_instrument);
		edit_equipment = (EditText) findViewById(R.id.edit_equipment);
		edit_hygiene = (EditText) findViewById(R.id.edit_hygiene);
		
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.job_result, R.layout.spinner_item);
		job_spinner.setAdapter(adapter);
		instrument_spinner.setAdapter(adapter);
		equipment_spinner.setAdapter(adapter);
		adapter = ArrayAdapter.createFromResource(
				this, R.array.hygiene_result, R.layout.spinner_item);
		hygiene_spinner.setAdapter(adapter);
		
		edit_deparment.setText(SettingLoader.getGuardName(this));
	}
	
	private OnClickListener signListener1 = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			WritePadDialog writeTabletDialog = new WritePadDialog(
					ShiftChangeActivity.this, new DialogListener() {
						@Override
						public void refreshActivity(Object object) {							

							Bitmap mSignBitmap = (Bitmap) object;
							s1 = createFile(mSignBitmap);
							/*BitmapFactory.Options options = new BitmapFactory.Options();
							options.inSampleSize = 15;
							options.inTempStorage = new byte[5 * 1024];
							Bitmap zoombm = BitmapFactory.decodeFile(signPath, options);*/	
							edit_duty_man.setVisibility(View.VISIBLE);
							edit_duty_man.setImageBitmap(mSignBitmap);
							btn_sign_jiaoban.setVisibility(View.GONE);
						}
					});
			writeTabletDialog.show();
		}
	};
	
	private OnClickListener signListener2 = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			WritePadDialog writeTabletDialog = new WritePadDialog(
					ShiftChangeActivity.this, new DialogListener() {
						@Override
						public void refreshActivity(Object object) {							

							Bitmap mSignBitmap = (Bitmap) object;
							s2 = createFile(mSignBitmap);
							/*BitmapFactory.Options options = new BitmapFactory.Options();
							options.inSampleSize = 15;
							options.inTempStorage = new byte[5 * 1024];
							Bitmap zoombm = BitmapFactory.decodeFile(signPath, options);*/														
							edit_device.setVisibility(View.VISIBLE);
							edit_device.setImageBitmap(mSignBitmap);
							btn_sign_jieban.setVisibility(View.GONE);
						}
					});
			writeTabletDialog.show();
		}
	};
	
	private OnClickListener signListener3 = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			WritePadDialog writeTabletDialog = new WritePadDialog(
					ShiftChangeActivity.this, new DialogListener() {
						@Override
						public void refreshActivity(Object object) {							

							Bitmap mSignBitmap = (Bitmap) object;
							s3 = createFile(mSignBitmap);
							/*BitmapFactory.Options options = new BitmapFactory.Options();
							options.inSampleSize = 15;
							options.inTempStorage = new byte[5 * 1024];
							Bitmap zoombm = BitmapFactory.decodeFile(signPath, options);*/														
							edit_break.setImageBitmap(mSignBitmap);
							edit_break.setVisibility(View.VISIBLE);
							btn_sign_banzhang.setVisibility(View.GONE);
						}
					});
			writeTabletDialog.show();
		}
	};

	
	/**
	 * 创建手写签名文件
	 * 
	 * @return
	 */
	private String createFile(Bitmap bitmap) {
		ByteArrayOutputStream baos = null;
		String _path = Utils.getCachePath().getAbsolutePath()+System.currentTimeMillis() + ".jpg";
		try {
			baos = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 60, baos);
			byte[] photoBytes = baos.toByteArray();
			if (photoBytes != null) {
				new FileOutputStream(new File(_path)).write(photoBytes);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null)
					baos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return _path;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			super.onBackPressed();
			break;
		case R.id.btn_refresh:
			new AlertDialog.Builder(this)
					.setTitle("确认交接")
					.setIcon(android.R.drawable.ic_menu_info_details)
					.setMessage("确认交接吗？")
					.setCancelable(false)
					.setPositiveButton(
							getResources().getString(R.string.confirm),
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									confirmShift();
								}
							})
					.setNegativeButton(
							getResources().getString(R.string.cancel),
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							}).show();
			break;
		default:
			break;
		}
	}

	private void confirmShift() {
		String job = null;
		if("其他".equals(getSelectionValue(R.array.job_result, job_spinner.getSelectedItemPosition()))) {
			job = edit_job_assets.getText().toString();
			if(Utils.isNullOrEmpty(job)) {
				Utils.showToast(this, "请填写岗位公物");
				return ;
			}
		}else {
			job = (getSelectionValue(R.array.job_result, job_spinner.getSelectedItemPosition()));
		}
		String instrument = null;
		if("其他".equals(getSelectionValue(R.array.job_result, instrument_spinner.getSelectedItemPosition()))) {
			instrument = edit_instrument.getText().toString();
			if(Utils.isNullOrEmpty(instrument)) {
				Utils.showToast(this, "请填写警用器械");
				return ;
			}
		}else {
			instrument = (getSelectionValue(R.array.job_result, instrument_spinner.getSelectedItemPosition()));
		}
		
		
		String equipment = null;
		if("其他".equals(getSelectionValue(R.array.job_result, equipment_spinner.getSelectedItemPosition()))) {
			equipment = edit_equipment.getText().toString();
			if(Utils.isNullOrEmpty(equipment)) {
				Utils.showToast(this, "请填写消防器材");
				return ;
			}
		}else {
			equipment = (getSelectionValue(R.array.job_result, equipment_spinner.getSelectedItemPosition()));
		}
		
		String hygiene = (getSelectionValue(R.array.hygiene_result, hygiene_spinner.getSelectedItemPosition()));

		Log.e("shift", "job is " + job + " instrument is " + instrument + " equipment is " + equipment + " hygiene is " + hygiene);
		ShiftChange shift = new ShiftChange();
		shift.setDid(SettingLoader.getDepartNum(this));
		shift.setAid(SettingLoader.getAreaNum(this));
		shift.setNid1(SettingLoader.getGuardNum(this));
		shift.setNid2(getSelectionValue(guardList, carry_spinner.getSelectedItemPosition()));
		shift.setS1(getContent(s1));
		shift.setS2(getContent(s2));
		shift.setS3(getContent(s3));
		shift.setLog(job+"||"+instrument+"||"+equipment+"||"+hygiene);
		
		ShiftChangeApi api = new ShiftChangeApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {
			
			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
				JSONObject jsonEntity = apiResult.getJsonEntity();
				Log.e("aa", jsonEntity.toString());
				//{"d":{"__type":"OperatorReturn:r","r":"1"},"t":0}

				if (jsonEntity != null) {

					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							JSONObject object = jsonEntity.getJSONObject("d");
							if(object!=null) {
								String result = object.getString("r");
								if(!Utils.isNullOrEmpty(result)&&Integer.parseInt(result)>0) {
									Utils.showToast(ShiftChangeActivity.this, "交接成功");
									gotoActivity(HomeActivity.class);
								}else {
									Utils.showToast(ShiftChangeActivity.this, "交接失败");
								}
							}
							break;
						case 1:// 数组
							
							break;
						case -1:// 错误
							break;

						default:
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public <T> void onReturnLoading(int requestCode) {
				showDialog(ID_LOADING);
				
			}
			
			@Override
			public <T> void onReturnFailResult(int requestCode, ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
			}
		});
		api.shiftChange(1, this, shift);
	
	}
	
	private String getContent(String filepath) {
		try {
			if(!Utils.isNullOrEmpty(filepath)) {
				File file = new File(filepath);
				if(file!=null&&file.exists()) {
					Log.e("File", "file exists");
					FileInputStream fis = new FileInputStream(file);
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					byte[] buffer = new byte[1024];
					int count = 0;
					while ((count = fis.read(buffer)) >= 0) {
						baos.write(buffer, 0, count);
					}
					fis.close();
					return new String(Base64.encode(baos.toByteArray())); // 进行Base64编码
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private String getSelectionValue(int arrayId, int position) {
		String[] array = getResources().getStringArray(arrayId);
		return array[position];
	}
	private String getSelectionValue(ArrayList<GuardEntity> list, int position) {
		if(list!=null) {
			return list.get(position).getNid();
		}
		return null;
	}
	
	private void gotoActivity(Class<HomeActivity> classes) {
		Intent intent = new Intent(this,classes);
		startActivity(intent);
		finish();
	}


	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		switch (parent.getId()) {
		case R.id.spinner1:
			if("其他".equals(getSelectionValue(R.array.job_result, job_spinner.getSelectedItemPosition()))) {
				edit_job_assets.setVisibility(View.VISIBLE);
			}else {
				edit_job_assets.setVisibility(View.GONE);
			}
			break;
		case R.id.spinner2:
			if("其他".equals(getSelectionValue(R.array.job_result, instrument_spinner.getSelectedItemPosition()))) {
				edit_instrument.setVisibility(View.VISIBLE);
			}else {
				edit_instrument.setVisibility(View.GONE);
			}
			break;
		case R.id.spinner3:
			if("其他".equals(getSelectionValue(R.array.job_result, equipment_spinner.getSelectedItemPosition()))) {
				edit_equipment.setVisibility(View.VISIBLE);
			}else {
				edit_equipment.setVisibility(View.GONE);
			}
			break;

		default:
			break;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub
		
	}
}
